/*
 * ***********************************************************
 * @Project: SCVHDemo
 * @File: MainActivity.java
 * @LastEditTime: 2024/11/17 15:32:22
 * @Author: chadm
 * ***********************************************************
 */

package com.example.client2;

import static com.example.ipclibrary.MessageUtil.KEY_DISPLAY_ID;
import static com.example.ipclibrary.MessageUtil.KEY_HEIGHT;
import static com.example.ipclibrary.MessageUtil.KEY_HOST_TOKEN;
import static com.example.ipclibrary.MessageUtil.KEY_TOUCH_EVENT;
import static com.example.ipclibrary.MessageUtil.KEY_WIDTH;
import static com.example.ipclibrary.MessageUtil.MSG_SEND_SURFACE_INFO;
import static com.example.ipclibrary.MessageUtil.MSG_TOUCH_EVENT;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceControlViewHost;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.ipclibrary.MessageUtil;

public class MainActivity extends AppCompatActivity {

    final String TAG = MainActivity.class.getSimpleName();
    private Messenger mServiceMessenger;
    private SurfaceControlViewHost mViewHost;
    private int count = 0;
    private View view;
    private SurfaceControlViewHost.SurfacePackage pkg;
    private Messenger mLocalMessenger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        mLocalMessenger = new Messenger(new InnerHandler(Looper.getMainLooper()));

        Intent service = new Intent("com.demo.hostservice");
        service.setPackage("com.example.host");
        bindService(service,new MessageConnect(), Context.BIND_AUTO_CREATE);
    }

    class InnerHandler extends Handler {
        public InnerHandler(Looper looper) {
            super(looper);
        }

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.i(TAG,"handleMessage: " + msg.what);
            switch (msg.what) {
                case MSG_SEND_SURFACE_INFO:
                    Bundle bundle = msg.getData();
                    IBinder hostToken = bundle.getBinder(KEY_HOST_TOKEN);
                    int dispalyId = bundle.getInt(KEY_DISPLAY_ID);
                    int width = bundle.getInt(KEY_WIDTH);
                    int height = bundle.getInt(KEY_HEIGHT);

                    if(mViewHost == null) {
                        Display display = getSystemService(DisplayManager.class).getDisplay(dispalyId);
                        mViewHost = new SurfaceControlViewHost(MainActivity.this,display,hostToken);
                        view = LayoutInflater.from(MainActivity.this).inflate(R.layout.host_view,null);
                        view.setOnTouchListener((v,event) -> {
                            Log.i(TAG,"onTouch");
                            TextView text = view.findViewById(R.id.title);
                            text.setText(getString(R.string.title, ++count));
                            return true;
                        });
                        mViewHost.setView(view,width,height);
                        pkg = mViewHost.getSurfacePackage();
                    }

                    Message toHost = MessageUtil.obtainSurfacePackage(pkg,MainActivity.this.getPackageName());
                    try {
                        mServiceMessenger.send(toHost);
                        Log.i(TAG,"send surface package to host");
                    } catch (RemoteException e) {
                        Log.e(TAG,e.toString());
                    }
                    break;
                case MSG_TOUCH_EVENT:
                    MotionEvent event = msg.getData().getParcelable(KEY_TOUCH_EVENT);
                    view.dispatchTouchEvent(event);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    private class MessageConnect implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG,"onServiceConnected");
            mServiceMessenger = new Messenger(service);

            // bind service成功后，注册到host
            Message msg = MessageUtil.obtainRegClient(MainActivity.this.getPackageName());
            msg.replyTo = mLocalMessenger;
            try {
                mServiceMessenger.send(msg);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mServiceMessenger = null;
        }
    }
}